﻿using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Update.Internal;
using Microsoft.EntityFrameworkCore.Update;
using System.Diagnostics.CodeAnalysis;

namespace MathTutorPro.Data
{
    public class MigrationsModelDifferWithoutForeignKey : MigrationsModelDiffer
    {
        public MigrationsModelDifferWithoutForeignKey(IRelationalTypeMappingSource typeMappingSource, IMigrationsAnnotationProvider migrationsAnnotationProvider, IRowIdentityMapFactory rowIdentityMapFactory, CommandBatchPreparerDependencies commandBatchPreparerDependencies) : base(typeMappingSource, migrationsAnnotationProvider, rowIdentityMapFactory, commandBatchPreparerDependencies)
        {
        }

        public override IReadOnlyList<MigrationOperation> GetDifferences(IRelationalModel? source, IRelationalModel? target)
        {
            //var operations = base.GetDifferences(source, target)
            //    .Where(op => !(op is AddForeignKeyOperation))
            //    .Where(op => !(op is DropForeignKeyOperation))
            //    .ToList();

            //foreach (var operation in operations.OfType<CreateTableOperation>())
            //    operation.ForeignKeys?.Clear();

            var operations = base.GetDifferences(source, target)
                .Where(op => !IsNonAspNetForeignKeyOperation(op)) // 过滤非AspNet表的外键操作
                .ToList();

            // 清除非AspNet表的CreateTable外键
            foreach (var operation in operations.OfType<CreateTableOperation>().Where(op => !IsAspNetTable(op.Name)))
            {
                operation.ForeignKeys?.Clear();
            }

            return operations;
        }

        private bool IsAspNetTable(string tableName)
        {
            // 根据表名前缀判断是否为Identity框架表
            return tableName?.StartsWith("AspNet") == true;
        }
        private bool IsNonAspNetForeignKeyOperation(MigrationOperation operation)
        {
            // 处理添加外键：非AspNet表的外键需要排除
            if (operation is AddForeignKeyOperation addFk)
            {
                return !IsAspNetTable(addFk.Table);
            }

            // 处理删除外键：非AspNet表的外键需要排除
            if (operation is DropForeignKeyOperation dropFk)
            {
                return !IsAspNetTable(dropFk.Table);
            }

            return false;
        }
    }
}

